package com.ruoyi.framework.jwt.filter;

import com.ruoyi.common.config.JwtConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.jwt.JwtUtils;
import com.ruoyi.framework.jwt.service.JwtTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * JWT认证过滤器
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter
{
    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenService jwtTokenService;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException
    {
        // 检查是否启用JWT认证
        if (!jwtConfig.getEnabled())
        {
            filterChain.doFilter(request, response);
            return;
        }

        String requestURI = request.getRequestURI();
        
        // 检查是否是JWT认证路径
        if (!requestURI.startsWith(jwtConfig.getPathPrefix()))
        {
            filterChain.doFilter(request, response);
            return;
        }

        // 检查是否在排除路径中
        if (isExcludePath(requestURI))
        {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取Token
        String token = getTokenFromRequest(request);
        if (StringUtils.isEmpty(token))
        {
            handleAuthenticationError(response, "Token不能为空");
            return;
        }

        try
        {
            // 验证Token
            if (!JwtUtils.validateToken(token, jwtConfig.getSecret()))
            {
                handleAuthenticationError(response, "Token无效或已过期");
                return;
            }

            // 检查Token是否在黑名单中
            String tokenId = JwtUtils.getTokenId(token, jwtConfig.getSecret());
            if (StringUtils.isNotEmpty(tokenId) && jwtTokenService.isTokenBlacklisted(tokenId))
            {
                handleAuthenticationError(response, "Token已被禁用");
                return;
            }

            // 获取用户信息并设置到请求中
            Long userId = JwtUtils.getUserId(token, jwtConfig.getSecret());
            String username = JwtUtils.getUsername(token, jwtConfig.getSecret());
            
            if (userId != null && StringUtils.isNotEmpty(username))
            {
                request.setAttribute("userId", userId);
                request.setAttribute("username", username);
                request.setAttribute("tokenId", tokenId);
                
                log.debug("JWT认证成功，用户ID: {}, 用户名: {}", userId, username);
            }
            else
            {
                handleAuthenticationError(response, "Token中用户信息无效");
                return;
            }
        }
        catch (Exception e)
        {
            log.error("JWT认证失败: {}", e.getMessage());
            handleAuthenticationError(response, "Token验证失败");
            return;
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中获取Token
     * 
     * @param request 请求对象
     * @return Token字符串
     */
    private String getTokenFromRequest(HttpServletRequest request)
    {
        String bearerToken = request.getHeader(jwtConfig.getTokenHeader());
        if (StringUtils.isNotEmpty(bearerToken) && bearerToken.startsWith(jwtConfig.getTokenPrefix()))
        {
            return bearerToken.substring(jwtConfig.getTokenPrefix().length());
        }
        return null;
    }

    /**
     * 检查是否是排除路径
     * 
     * @param requestURI 请求URI
     * @return 是否排除
     */
    private boolean isExcludePath(String requestURI)
    {
        return Arrays.stream(jwtConfig.getExcludePaths())
                .anyMatch(pattern -> pathMatcher.match(pattern, requestURI));
    }

    /**
     * 处理认证错误
     * 
     * @param response 响应对象
     * @param message 错误消息
     */
    private void handleAuthenticationError(HttpServletResponse response, String message)
    {
        try
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            
            AjaxResult result = AjaxResult.error(message);
            ServletUtils.renderString(response, result.toString());
        }
        catch (Exception e)
        {
            log.error("处理认证错误失败: {}", e.getMessage());
        }
    }
}